package com.candy.candylog.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.candy.candylog.business.entity.Order;
import com.candy.candylog.business.entity.Product;
import com.candy.candylog.business.mapper.OrderMapper;
import com.candy.candylog.business.service.IOrderService;
import com.candy.candylog.business.service.IProductService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2024/5/24 15:10
 * @Description 描述
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class IOrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private final IProductService productService;

    Lock lock = new ReentrantLock();

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void buy(Integer proId, Integer num) {
        log.info("购买商品 proId = {}, num = {}", proId, num);
        Product product = productService.getById(proId);
        log.info("产品数量：{}", product);
        if (product.getNum() >= num) {
            product.setNum(product.getNum() - num);
            log.info("扣减后的商品信息：{}", product);
            productService.updateById(product);
            Order order = new Order();
            order.setProId(proId);
            order.setNum(num);
            baseMapper.insert(order);
            log.info("订单详情：{}", order);
        } else {
            log.error("商品数量不够");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void buyError(Integer proId, Integer num) {
        lock.lock();
        try {
            buy(proId, num);
        } catch (Exception e) {
            log.error("发生异常", e);
        } finally {
            lock.unlock();
        }
    }

}
